package person.bing.fbcloud.util;
//登录功能用于解密的方法
//第一个参数是加密的密文，第二个是秘钥，第三个是偏移量；秘钥和偏移量应和JS端一致

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
 * @author: mengfanbing
 * @date: 2019/10/9
 */
public class Test {
    /*public static void main(String[] args) {
        try {
            String s = decryptToLogin("4JL2V5INbDoFkqeDxAnRAw==", "tkcloudtkcloud11", "tkcloudtkcloud11");
            System.out.println(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/


    public static String decryptToLogin(String sSrc, String sKey, String IV) throws Exception {

        // 判断Key是否正确
        if (sKey == null) {
            System.out.print("Key为空null");
            return null;
        }
        // 判断Key是否为16位
        if (sKey.length() != 16) {
            System.out.print("Key长度不是16位");
            return null;
        }
        byte[] raw = sKey.getBytes("ASCII");

        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
        byte[] encrypted1 = Base64.decodeBase64(sSrc);//先用bAES64解密
        try {
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original);
            return originalString;
        } catch (Exception e) {
            return null;
        }
    }


}
